<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="职级管理">
        管理专家职级信息，包括院士、资深专家、其他专家等职级分类。
      </n-card>
    </div>
    <n-card :bordered="false" title="职级列表" class="mt-4">
      <n-space vertical :size="16">
        <!-- 搜索栏 -->
        <n-space justify="space-between">
          <n-space>
            <n-input
              v-model:value="searchParams.keyword"
              placeholder="请输入职级名称"
              style="width: 300px"
              clearable
            />
            <n-select
              v-model:value="searchParams.status"
              placeholder="状态筛选"
              :options="statusOptions"
              style="width: 150px"
              clearable
            />
            <n-button type="primary" @click="handleSearch">
              <template #icon>
                <n-icon>
                  <SearchOutline />
                </n-icon>
              </template>
              搜索
            </n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
          <n-button type="primary" @click="handleAdd">
            <template #icon>
              <n-icon>
                <AddOutline />
              </n-icon>
            </template>
            新增职级
          </n-button>
        </n-space>

        <!-- 数据表格 -->
        <n-data-table
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :pagination="pagination"
          :row-key="rowKey"
          @update:page="handlePageChange"
        />
      </n-space>
    </n-card>

    <!-- 新增/编辑弹窗 -->
    <n-modal
      v-model:show="showModal"
      :title="modalTitle"
      preset="card"
      style="width: 500px"
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="left"
        :label-width="100"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="职级名称" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入职级名称" style="width: 100%" />
        </n-form-item>
        <n-form-item label="职级等级" path="value">
          <n-input-number
            v-model:value="formData.value"
            placeholder="请输入职级等级"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formData.status">
            <n-space>
              <n-radio :value="1">启用</n-radio>
              <n-radio :value="0">禁用</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input-number
            v-model:value="formData.sort"
            placeholder="请输入排序值"
            :min="0"
            :max="999"
            style="width: 100%"
          />
        </n-form-item>
        <n-form-item label="备注" path="remark">
          <n-input
            v-model:value="formData.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showModal = false">取消</n-button>
          <n-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, h, computed } from 'vue';
import { useMessage, useDialog, NSwitch } from 'naive-ui';
import {
  SearchOutline,
  AddOutline,
  CreateOutline,
  TrashOutline,
} from '@vicons/ionicons5';
import { createIndexColumn } from '@/utils/tableUtil';

const message = useMessage();
const dialog = useDialog();

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: null as number | null,
});

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
];

// 表格数据
const loading = ref(false);
const tableData = ref<any[]>([]);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageCount: 0,
  onChange: (page: number) => {
    pagination.page = page;
    loadData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    loadData();
  },
});

// 表格列定义
const columns = computed(() => [
  createIndexColumn({
    currentPage: pagination.page,
    pageSize: pagination.pageSize,
  }),
  { title: '职级名称', key: 'name', width: 150 },
  { title: '职级等级', key: 'value', width: 100 },
  { 
    title: '状态', 
    key: 'status', 
    width: 100,
    render: (row: any) => {
      return h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
        h(NSwitch, {
          value: row.status === 1,
          onUpdateValue: (value: boolean) => {
            // 更新数据中的状态
            row.status = value ? 1 : 0;
            console.log('状态切换:', row.id, value ? 1 : 0);
          }
        }),
        h('span', { style: 'font-size: 12px;' }, row.status === 1 ? '启用' : '禁用')
      ]);
    }
  },
  { title: '排序', key: 'sort', width: 100 },
  { title: '创建时间', key: 'createTime', width: 180 },
  { title: '备注', key: 'remark', width: 200 },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    render: (row: any) => {
      return h('div', [
        h(
          'n-button',
          {
            size: 'small',
            type: 'primary',
            ghost: true,
            onClick: () => handleEdit(row),
            style: 'margin-right: 8px',
          },
          { default: () => '编辑' }
        ),
        h(
          'n-button',
          {
            size: 'small',
            type: 'error',
            ghost: true,
            onClick: () => handleDelete(row),
          },
          { default: () => '删除' }
        ),
      ]);
    },
  },
]);

// 表单相关
const showModal = ref(false);
const modalTitle = ref('新增职级');
const submitLoading = ref(false);
const formRef = ref();
const formData = reactive({
  id: '',
  name: '',
  value: 1,
  status: 1,
  sort: 0,
  remark: '',
});

const rules = {
  name: {
    required: true,
    message: '请输入职级名称',
    trigger: 'blur',
  },
  value: {
    required: true,
    message: '请输入职级等级',
    trigger: 'blur',
  },
};

// 方法
const rowKey = (row: any) => row.id;

const loadData = () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    tableData.value = [
      {
        id: '1',
        name: '院士',
        value: 1,
        status: 1,
        sort: 1,
        createTime: '2024-01-15 10:30:00',
        remark: '最高专家等级',
      },
      {
        id: '2',
        name: '资深专家',
        value: 2,
        status: 1,
        sort: 2,
        createTime: '2024-01-15 10:30:00',
        remark: '高级专家等级',
      },
      {
        id: '3',
        name: '其他专家',
        value: 3,
        status: 1,
        sort: 3,
        createTime: '2024-01-15 10:30:00',
        remark: '普通专家等级',
      },
      {
        id: '4',
        name: '特邀专家',
        value: 4,
        status: 1,
        sort: 4,
        createTime: '2024-01-15 10:30:00',
        remark: '特殊邀请专家',
      },
      {
        id: '5',
        name: '青年专家',
        value: 5,
        status: 0,
        sort: 5,
        createTime: '2024-01-15 10:30:00',
        remark: '青年学者专家',
      },
    ];
    pagination.pageCount = 1;
    loading.value = false;
  }, 500);
};

const handleSearch = () => {
  pagination.page = 1;
  loadData();
};

const handleReset = () => {
  searchParams.keyword = '';
  searchParams.status = null;
  pagination.page = 1;
  loadData();
};

const handlePageChange = (page: number) => {
  pagination.page = page;
  loadData();
};

const handleAdd = () => {
  modalTitle.value = '新增职级';
  Object.assign(formData, {
    id: '',
    name: '',
    value: 1,
    status: 1,
    sort: 0,
    remark: '',
  });
  showModal.value = true;
};

const handleEdit = (row: any) => {
  modalTitle.value = '编辑职级';
  Object.assign(formData, row);
  showModal.value = true;
};

const handleDelete = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除等级"${row.name}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      message.success('删除成功');
      loadData();
    },
  });
};

const handleSubmit = () => {
  formRef.value?.validate((errors: any) => {
    if (!errors) {
      submitLoading.value = true;
      setTimeout(() => {
        message.success(formData.id ? '更新成功' : '创建成功');
        showModal.value = false;
        submitLoading.value = false;
        loadData();
      }, 1000);
    }
  });
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.n-layout-page-header {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
</style> 